package com.mengwen.backstage.controller;


import com.mengwen.backstage.manager.MenuManager;
import com.mengwen.backstage.pojo.Partner;

import com.mengwen.backstage.service.PartnerService;
import com.mengwen.backstage.util.MD5Util;
import com.mengwen.backstage.util.WeixinUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.lang.String;

@Controller
public class LoginController {

    @Autowired
    PartnerService partnerService;

    // 合伙人进入登录页面
    @RequestMapping("/partner/login")
    public String partnerToLogin(){
        System.out.println("原来是合伙人");
        return "partner_login";
    }


    // 管理员进入登录页面
    @RequestMapping("/admin/login")
    public String adminToLogin(){
        System.out.println("是管理员大人");
        return "admin_login";
    }
    // 首次当了将openid注入数据库
    // 管理员进入登录页面
    @RequestMapping("/mengwen/admin/login")
    public String adminLogin(HttpServletResponse response, HttpServletRequest httpServletRequest, Model model) throws IOException, ServletException {




        String accountNumber = httpServletRequest.getParameter("account_number");
        String password = httpServletRequest.getParameter("password");
        String md5Password = MD5Util.md5Encrypt32Upper(password);
        System.out.println("账号：" + accountNumber);


        Partner partner = partnerService.login(accountNumber, md5Password);
        if (partner == null) {
            // 账号密码不正确：
            model.addAttribute("errorMsg","账号或密码错误");
            System.out.println("账号或密码错误");
            return "partner_login";
        }else {
            System.out.println("首次登录");
            String path = MenuManager.REAL_URL + "/mengwen/userInfo/first_login_invoke?account_number="
                    + accountNumber + "&md5Password=" + md5Password ;
            System.out.println(path);
            path = URLEncoder.encode(path,"UTF-8");
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                    + "appid="+MenuManager.appId
                    + "&redirect_uri="+ path
                    + "&response_type=code"
                    + "&scope=snsapi_base"
                    +"&state=mwoauth#wechat_redirect";
            model.addAttribute("partner",partner);

            response.sendRedirect(url);
            System.out.println("222222222222222222222222222");
//            httpServletRequest.getRequestDispatcher(url).forward(httpServletRequest,response);
            return "admin_back_management";

        }


    }



    // 合伙人登录
    // 首次当了将openid注入数据库
    @RequestMapping("/mengwen/partner/login")
    public String partnerLogin(HttpServletResponse response, HttpServletRequest httpServletRequest, Model model) throws IOException, ServletException {



        /////////////////////////////////////////
        System.out.println("合伙人陆 动次打次的a");
        String accountNumber = httpServletRequest.getParameter("account_number");
        String password = httpServletRequest.getParameter("password");
        String md5Password = MD5Util.md5Encrypt32Upper(password);
        System.out.println("战鼓" + accountNumber);


        Partner partner = partnerService.login(accountNumber, md5Password);
        if (partner == null) {
            // 账号密码不正确：
            model.addAttribute("errorMsg","账号或密码错误");
            System.out.println("账号或密码错误");
            return "partner_login";
        }else {
            System.out.println("首次登录");
            String path = MenuManager.REAL_URL + "/mengwen/userInfo/first_login_invoke?account_number="
                    + accountNumber + "&md5Password=" + md5Password ;
            System.out.println(path);
            path = URLEncoder.encode(path,"UTF-8");
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                    + "appid="+MenuManager.appId
                    + "&redirect_uri="+ path
                    + "&response_type=code"
                    + "&scope=snsapi_base"
                    +"&state=mwoauth#wechat_redirect";
            model.addAttribute("partner",partner);

            response.sendRedirect(url);
            System.out.println("222222222222222222222222222");
//            httpServletRequest.getRequestDispatcher(url).forward(httpServletRequest,response);
            return "partner_page";

        }


    }


    @RequestMapping("/mengwen/userInfo/first_login_invoke")
    public String getFirstLoginOpenid(HttpServletRequest request,Model model){
        String code = request.getParameter("code");
        String accountNumber = request.getParameter("account_number");
        String md5Password = request.getParameter("md5Password");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid=" + MenuManager.appId
                + "&secret=" + MenuManager.appSecret
                + "&code=" + code
                + "&grant_type=authorization_code";


        JSONObject accessTokenAndOpenidjsonObject = WeixinUtil.httpRequest(url, "POST", null);

        String openid = accessTokenAndOpenidjsonObject.getString("openid");

        int count = partnerService.updateOpenidByAccountNumberAndPassword(openid, accountNumber, md5Password);
        if (count != 1) {
            System.out.println("插入失败。");
            return "error_page";
        }else {
            System.out.println("插入成功");
            Partner newPartner = partnerService.findByAccountNumberAndPassword(accountNumber,md5Password);
            System.out.println(newPartner);
            System.out.println("========================================");
            model.addAttribute("partner",newPartner);
            Partner partner4 = (Partner) model.getAttribute("partner");
            System.out.println(partner4);
            return "partner_page";
        }



    }

    public static void main(String[] args) {
        String s = MD5Util.md5Encrypt32Upper("123");
        System.out.println(s);
    }



}
